import request from '@/utils/request'
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage'
import { SAVE_ALLCHANNELS, SAVE_CHANNELS } from '../constants/home'
export const saveUserChannels = (payload) => {
  return {
    type: SAVE_CHANNELS,
    payload,
  }
}

export const getUserChannels = () => {
  return async (dispatch) => {
    if (hasToken()) {
      const res = await request.get('user/channels')
      dispatch(saveUserChannels(res.data.channels))
    } else {
      const channels = getLocalChannels()
      if (channels) {
        // 2. 没有token,从本地获取频道数据
        dispatch(saveUserChannels(channels))
      } else {
        // 没有token, 且本地没有channels数据
        const res = await request.get('user/channels')
        dispatch(saveUserChannels(res.data.channels))
        // 保存到本地
        setLocalChannels(res.data.channels)
      }
    }
  }
}

export const saveAllChannels = (payload) => {
  return {
    type: SAVE_ALLCHANNELS,
    payload,
  }
}

export const getAllChannels = () => {
  return async (dispatch) => {
    const res = await request.get('channels')
    dispatch(saveAllChannels(res.data.channels))
  }
}
